﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Media;

using FirstFloor.Documents;

namespace FirstFloor.Documents.Presentation.Metadata
{
    /// <summary>
    /// Represents the relationships collection node.
    /// </summary>
    public class RelationshipsCollectionNode
        : Node
    {
        private PageContent page;
        private XpsPart part;

        /// <summary>
        /// Initializes a new instance of the <see cref="RelationshipsCollectionNode"/> class.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="part">The part.</param>
        /// <param name="options">The options.</param>
        public RelationshipsCollectionNode(PageContent page, XpsPart part, ViewModelOptions options)
            : base(options)
        {
            this.page = page;
            this.part = part;
            this.part.PropertyChanged += part_PropertyChanged;
        }

        private void part_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Relationships") {
                //ensure UI gets updated
                OnPropertyChanged("Text");
                OnPropertyChanged("Children");      
            }
        }

        /// <summary>
        /// Gets the page that is associated with this node instace.
        /// </summary>
        /// <value>The page.</value>
        public override PageContent Page
        {
            get { return this.page; }
        }

        /// <summary>
        /// Gets the text.
        /// </summary>
        /// <value>The text.</value>
        public override string Text
        {
            get
            {
                if (this.part.Relationships == null) {
                    return string.Format("Relationships ({0})", '?');
                }
                return string.Format("Relationships ({0})", this.part.Relationships.Count());
            }
        }

        /// <summary>
        /// Gets the icon.
        /// </summary>
        /// <value>The icon uri.</value>
        public override string Icon
        {
            get { return "/FirstFloor.Documents.Presentation;component/Assets/Icons/folder_link.png"; }
        }

        /// <summary>
        /// Gets the child nodes.
        /// </summary>
        /// <value>The nodes.</value>
        public override IEnumerable<Node> Children
        {
            get
            {
                if (this.part.Relationships != null) {
                    foreach (PackageRelationship relationship in this.part.Relationships.OrderBy(r => { return r.TargetUri.OriginalString; })) {
                        yield return new RelationshipNode(this.page, relationship, this.Options);
                    }
                }
            }
        }
    }
}
